package com.clei.netty.util;

/**
 * 字节数组转义处理器
 *
 * @author Y
 * @date 2022-10-24
 */
public class ByteEscapeHandler {
    /**
     * from 例{0X7E,0X7D}
     */
    private final byte[] from;

    /**
     * to 例{{0X7E,0X02},{0X7E,0X01}}
     */
    private final byte[][] to;

    public ByteEscapeHandler(byte[] from, byte[][] to) {
        // to的长度必须和from的长度一致，且to[i]的每个元素的的长度只能为2
        this.from = from;
        this.to = to;
    }

    /**
     * 转义
     *
     * @param data 原始数据
     * @return 转义后的数据
     */
    public byte[] escape(byte[] data) {
        int length = data.length;
        int resLength = length;
        for (byte b : data) {
            for (byte f : this.from) {
                if (b == f) {
                    resLength++;
                    break;
                }
            }
        }
        byte[] res = new byte[resLength];
        for (int i = 0, j = 0; i < length; i++, j++) {
            byte b = data[i];
            // 是否有对应from
            boolean change = false;
            for (int k = 0; k < this.from.length; k++) {
                byte f = this.from[k];
                if (b == f) {
                    change = true;
                    res[j] = this.to[k][0];
                    res[++j] = this.to[k][1];
                    break;
                }
            }
            if (!change) {
                res[j] = b;
            }
        }
        return res;
    }

    /**
     * 还原
     *
     * @param data 转义后的数据
     * @return 原始数据
     */
    public byte[] escapeBack(byte[] data) {
        int length = data.length;
        int resLength = length;
        for (int i = 0; i < length - 1; i++) {
            for (int k = 0; k < this.to.length; k++) {
                byte[] toArr = this.to[k];
                if (data[i] == toArr[0] && data[i + 1] == toArr[1]) {
                    resLength--;
                    i++;
                    break;
                }
            }
        }
        byte[] res = new byte[resLength];
        int i = 0;
        for (int j = 0; i < length - 1; i++, j++) {
            boolean change = false;
            for (int k = 0; k < this.to.length; k++) {
                byte[] toArr = this.to[k];
                if (data[i] == toArr[0] && data[i + 1] == toArr[1]) {
                    res[j] = this.from[k];
                    i++;
                    change = true;
                    break;
                }
            }
            if (!change) {
                res[j] = data[i];
            }
        }
        // 最后两个byte不符合to
        if (i != length) {
            res[res.length - 1] = data[data.length - 1];
        }
        return res;
    }
}
